const { Controller } = require("egg");
const jwt = require("jsonwebtoken");
const key = "aaaaa";

class UserController extends Controller {
  async login() {
    const { ctx } = this;
    const { userName, passWord } = ctx.request.body;
    const data = await ctx.app.mysql.get("user", {
      userName,
    });
    if (data) {
      if (data.passWord === passWord) {
        const token = jwt.sign(
          {
            userName,
            id: data.id,
          },
          key
        );
        ctx.body = {
          code: 1,
          message: "登录成功",
          token,
        };
      } else {
        ctx.body = {
          code: 0,
          message: "账号密码不匹配",
        };
      }
    } else {
      ctx.body = {
        code: 0,
        message: "请先注册",
      };
    }
  }

  async getUserList() {
    const { ctx } = this;
    const { pageSize, pageNum } = ctx.query;
    try {
      const data = await ctx.app.mysql.select("user_info");
      // const data = await ctx.app.mysql.query(`SELECT * FROM 'user_info' LIMIT ${ pageNum * pageSize } OFFSET ${ (pageNum - 1) * pageSize }`)
      ctx.body = {
        code: 1,
        message: "获取列表成功",
        data,
      };
    } catch {
      ctx.body = {
        code: 0,
        message: "sql错误",
      };
    }
  }

  // 新增接口
  async addUser() {
    const { ctx } = this;
    const userInfo = ctx.request.body;
    const data = await ctx.app.mysql.insert("user_info", userInfo);
    if (data.affectedRows === 1) {
      ctx.body = {
        code: 1,
        message: "新增成功",
      };
    }
  }

  // 删除接口
  async delUser() {
    const { ctx } = this;
    const id = ctx.query.id;
    const data = await ctx.app.mysql.delete("user_info", {
      id,
    });
    if (data.affectedRows === 1) {
      ctx.body = {
        code: 1,
        message: "删除成功",
      };
    }
  }

  // 编辑接口
  async editItem() {
    const { ctx } = this;
    const editInfo = ctx.request.body;
    const data = await ctx.app.mysql.update("user_info", editInfo);
    if (data.affectedRows === 1) {
      ctx.body = {
        code: 1,
        message: "编辑成功",
      };
    }
  }

  // 获取用户信息
  async getUserInfo() {
    const { ctx } = this;
    const { id } = jwt.verify(ctx.request.header.authorization, key);
    console.log("1111111111", id);
    const data = await ctx.app.mysql.get("userinfo", {
      id,
    });
    ctx.body = {
      code: 1,
      message: "获取用户信息成功",
      data,
    };
  }

  async userSearch() {
    const { ctx } = this;
    const value = ctx.query.title; // 从查询参数中获取搜索关键词
    // 假设这里是直接在 controller 中进行模糊搜索订单表
    const list = await this.app.mysql.query(
      `SELECT * FROM user_info WHERE userName LIKE '%${value}%'`
    );
    ctx.body = {
      code: 1,
      message: "搜索成功",
      list,
    };
  }
}

// post  put      ctx.request.body
// get   delete   ctx.query

module.exports = UserController;
